/**
 * <p>enhanceformpanel的控制类</p>
 * <p>对象新增后会重新载入带入主键值</p>
 * 继承自Ext.app.Controller

 * @module Ext-ux-cceaf-controller
 * @class cceaf.controller.EnhanceFormPanelCtrl
 * @extends Ext.app.Controller
 * @since 1.0
 */
Ext.define('cceaf.controller.EnhanceFormPanelCtrl',{
	extend: 'Ext.app.Controller', 
	requires: [
	    
    ],
	
    constructor: function(config){
		config = config || {};
		
		config = Ext.applyIf(config || {}, {

		});

		cceaf.controller.EnhanceFormPanelCtrl.superclass.constructor.apply(this, arguments);
	},

	/**
     * 监听事件
     */
    init: function() {
    	//控制层需控制视图的xtype
    	var controlledViewXType = this.controlledViewXType;
    	if (!controlledViewXType) {
    		//控制名称
    		var className = this.self.getName();
    		alert('必须设置控制层' + className + '需控制视图的xtype，即controlledViewXType属性！');
    		return;
    	}
    	
    	//构建初始化的事件监听
    	var eventTemplate = "this.control({" + 
	    	"'aaaaa': {" +
	    	"	afterrender: this.initPage" +
	        "}," +
        	"'aaaaa #btnAdd': {" + 
            "    click: this.page_add" + 
            "}," + 
            "'aaaaa #btnImport': {" + 
            "    click: this.page_import" + 
            "}," + 
            "'aaaaa #btnSave': {" + 
            "    click: this.page_save" + 
            "}," + 
            "'aaaaa #btnSend': {" + 
            "    click: this.page_send" + 
            "}," + 
            "'aaaaa #btnCancel': {" + 
            "    click: this.page_cancel" + 
            "}," + 
            "'aaaaa #btnClose': {" + 
            "    click: this.page_close" + 
            "}" + 
    	"});";
	    
	    var eventString = eventTemplate.replace(/aaaaa/gi, controlledViewXType);
	    eval(eventString);
        
        this.registerEvent();
        
        //标记已经初始化完成
        this.isInit = true;
    },
    
    /**
     * 对于动态加载controller模式
     * 第一次加载后设置为true，再次加载后不在执行init方法 
     * 
     * @property isInit 
     * @type Boolean
     * @default false
     */
    isInit: false,
    
    /**
     * 监听其他事件
     */
    registerEvent: function(){
    	
    },
    
    /**
     * 新增对象
     */
    page_add: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
    	 
     	//设置初值
    	controller.initAddPage();
     	
     	//以下设置按钮状态
     	var btnAdd = billForm.down('#btnAdd');
     	if (btnAdd) {
     		btnAdd.setDisabled(true);
     	}
     	
     	var btnImport = billForm.down('#btnImport');
     	if (btnImport) {
     		btnImport.setDisabled(true);
     	}
     	
     	var btnSave = billForm.down('#btnSave');
     	if (btnSave) {
     		btnSave.setDisabled(false);
     	}
     	
     	var btnCancel = billForm.down('#btnCancel');
     	if (btnCancel) {
     		btnCancel.setDisabled(false);
     	}
     	
     	var btnSend = billForm.down('#btnSend');
     	if (btnSend) {
     		btnSend.setDisabled(false);
     	}
    },
     
     /**
      * 取消新增或编辑，取消后回到初始界面
      */
    page_cancel: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
     	 
    	controller.setCancel();
      	
      	//以下设置按钮状态
      	var btnAdd = billForm.down('#btnAdd');
      	if (btnAdd) {
      		btnAdd.setDisabled(false);
      	}
      	
      	var btnImport = billForm.down('#btnImport');
      	if (btnImport) {
      		btnImport.setDisabled(false);
      	}
      	
      	var btnSave = billForm.down('#btnSave');
      	if (btnSave) {
      		btnSave.setDisabled(true);
      	}
      	
      	var btnCancel = billForm.down('#btnCancel');
      	if (btnCancel) {
      		btnCancel.setDisabled(true);
      	}
      	
      	var btnSend = billForm.down('#btnSend');
      	if (btnSend) {
      		btnSend.setDisabled(true);
      	}
    },
    
    /**
     * 导入数据
     */
    page_import: function(){
    	 cceaf.util.ExtHelper.showInfoDialog('开发中...');
    },
     
     
    /**
	 * 关闭弹出页面
	 *
     * @method page_close 
     */
    page_close: function(){
    	var billForm = this.getControlledView();
    	var addAndEditWin = billForm.up('window');
    	if (addAndEditWin) {
    		addAndEditWin.close();
    	}
    },
    
    /**
	 * 获取视图
	 *
     * @return {Ext.container.Container} 视图对象
     */
    getControlledView: function(){
    	var controlledViewXType = this.controlledViewXType;
    	var methodName = 'this.get' + controlledViewXType.substr(0,1).toUpperCase() + controlledViewXType.substring(1) + '()';
    	//alert(methodName);
    	
    	var view = eval(methodName);
    	return view;
    },
    
    /**
     * 进入页面时，设置初始值
     */
    initPage: function(){
    	var formPanel = this.getControlledView();
    	
    	var formFields = formPanel.query('.field');
		for(var i=0; formFields != null && i<formFields.length; i++){
    		var item = formFields[i];
    		item.setDisabled(true);
    	}
    },
    
    /**
     * 点击新增按钮时，设置初始值（所有field控件有效）
     */
    initAddPage: function(){
    	var formPanel = this.getControlledView();
    	
    	formPanel.form.reset();
        	
    	var formFields = formPanel.query('.field');
		for(var i=0; formFields != null && i<formFields.length; i++){
    		var item = formFields[i];
    		item.setDisabled(false);
    	}
    },
    
    /**
     * 点击取消按钮时，设置初始值（所有field控件有效）
     */
    setCancel: function(){
    	var formPanel = this.getControlledView();
    	
    	formPanel.form.reset();
        	
    	var formFields = formPanel.query('.field');
		for(var i=0; formFields != null && i<formFields.length; i++){
    		var item = formFields[i];
    		item.setDisabled(true);
    	}
    },
    
    /**
     * 校验表单数据的有效性，如果要校验需在子类加载
     *
     * @return {Boolean} 校验成功范围true
     */
    checkForm: function(){
    	return true;
    },
    
    /**
     * 表单载入数据后,设置特殊值表单值
     */
    initEditPage: function(){
    	
    },
    
    /**
     * 保存后的回调函数
     */
    saveCallback: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
    	
      	var btnAdd = billForm.down('#btnAdd');
    	if (btnAdd) {
    		btnAdd.setDisabled(false);
    	}
    	
    	var btnImport = billForm.down('#btnImport');
    	if (btnImport) {
    		btnImport.setDisabled(false);
    	}
    	
    	var btnSave = billForm.down('#btnSave');
    	if (btnSave) {
    		btnSave.setDisabled(false);
    	}
    	
    	var btnCancel = billForm.down('#btnCancel');
    	if (btnCancel) {
    		btnCancel.setDisabled(false);
    	}
    	
    	var btnSend = billForm.down('#btnSend');
    	if (btnSend) {
    		btnSend.setDisabled(false);
    	}
    },
    
    /**
     * 发送后的回调函数
     */
    sendCallback: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
    	
    	controller.initAddPage();
    },
    
    /**
     * 保存对象
     */
    page_save: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
    	if (!billForm.saveAction) {
    		alert('表单的saveAction没有设置！');
    		return;
    	}
    	 
     	var submitParam = {
     		 formSubmit: true, //form提交
     		 actionURL: billForm.saveAction,
 			 closePopWin: true,  //保存数据后关闭窗口
 			 formLoad: true //提交数据后不加载form的数据
     	};
 		
     	controller.page_submit(submitParam, controller.saveCallback);
    },
    
    /**
     * 用于工作任务的派发
     */
    page_send: function(){
    	var controller = this;
    	var billForm = controller.getControlledView();
    	
    	if (!billForm.sendAction) {
    		alert('表单的sendAction没有设置！');
    		return;
    	}
    	 
     	var submitParam = {
     		 formSubmit: true, //form提交
     		 actionURL: billForm.sendAction,
 			 closePopWin: true,  //保存数据后关闭窗口
 			 formLoad: false //提交数据后不加载form的数据
     	};
 
     	controller.page_submit(submitParam, controller.sendCallback);
    },
    
    /**
     * 提交页面
     * <br>示例： submitParam = { <br>
     * <br>	formSubmit: true, //false为ajax提交，true为form.submit <br>
     * <br>    actionURL： '',	//提交的action <br>
     * <br>    closePopWin: true, //保存数据后关闭窗口
     * <br>    params: {}, //提交的参数,json表达 <br>
     * <br>    formLoad: false, //提交数据后重新载入数据 <br>
     * <br> } 
     *
     * @method page_submit
     * @param {attribute} submitParam 提交参数 
     * @param {fn} callback 提交完成后调用的回调函数
     */
     page_submit: function(submitParam, callback){
    	 var controller = this;
    	 var billForm = controller.getControlledView();
     	
		var formSubmit = true;
		var closePopWin = true;
		var formLoad = false;
		var actionURL;

     	if (submitParam) {
     		if ( Ext.isDefined( submitParam.formSubmit )) {
     			formSubmit = submitParam.formSubmit;
     		}
     		if ( Ext.isDefined( submitParam.actionURL )) {
     			actionURL = submitParam.actionURL;
     		}
     		if ( Ext.isDefined( submitParam.closePopWin )) {
    			closePopWin = submitParam.closePopWin;
    		}
     		if ( Ext.isDefined( submitParam.params )) {
     			params = submitParam.params;
     		}
     		if ( Ext.isDefined( submitParam.formLoad )) {
     			formLoad = submitParam.formLoad;
     		}
     	}
     	
     	if (!actionURL) {
     		cceaf.util.ExtHelper.showInfoDialog("action 没有定义！");
     		return; 
     	}
 		
     	if(!billForm.form.isValid()){
 			return;
 		}
     	if(!controller.checkForm()){
     		return;
     	}

 		//组装主表 JSONString
 		var masterJSONData = new Object();
 		var formFields = billForm.query('.field');
 		
 		for(var i=0; formFields != null && i<formFields.length; i++){
     		var item = formFields[i];
     		var itemId = item.getName(); //注意:此处最好用getName,而不用getId
 			var itemValue = item.getValue();
 			
 			if(Ext.isDate(itemValue)){
 				itemValue = Ext.Date.format(itemValue,'Y-m-d');
 			}
 			
 			if (item.getXType() != 'filefield') {
 				var splitIndex = itemId.indexOf("-");
 				if( splitIndex > 0) {
 					cceaf.util.ExtHelper.showInfoDialog('必须设置' + itemId.substr(itemId, splitIndex) + '字段的name属性！');
 					return;
 				}
 				eval("masterJSONData." + itemId + " = '" + itemValue + "'");
 			}
     	}
 		
     	var masterJSONString = Ext.JSON.encode(masterJSONData);
       	//alert(masterJSONString);

 		if (formSubmit) {
 	     	billForm.form.submit({
 	        	url:  actionURL,
 	        	waitMsg : '正在保存数据...',
 	            success: function(from, action) { 
 	            	cceaf.util.ExtHelper.showInfoDialog(action.result.message); 
 	            	
 	            	if ( formLoad ) {
 	            		controller.page_load(action);
 	            	}
 	            	
 	            	if (callback) {
 	            		callback();
 	            	}
 	            },
 	            failure: function(from, action) {
 	            	cceaf.util.ExtHelper.processFailureAction(action);
 	            }
 	        });	
 	     
 	     } else {
 	     	Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
 	      	Ext.Ajax.request({
 	      		url:  actionURL,
 	      		params: {
	      			masterJSONString: masterJSONString
	      		},
 	      		success: function(response){
 	      			var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
 	      			
 	   			},
 	   			failure: function(response){
 	   				cceaf.util.ExtHelper.processAjaxRequest(response,false);
 	   			}
 	      	});
 	     }

     },
     
     /**
      * 页面提交成功后的数据重新载入，主要可以加载服务端生成的数据，如自增长的主键
      * 
      * @param {Ext.form.action.Action} action 
      */
     page_load: function(action){
    	 var controller = this;
    	 var billForm = controller.getControlledView();
 
    	 var masterkeys;
    	 if (!billForm.masterKeyIds) {
    		 alert('请设置表单的masterKeyIds！');
    		 return;
    	 } 
    	 masterkeys = billForm.masterKeyIds.split(',');
    	 
    	 var url;
    	 if (!billForm.findByKeyAction) {
    		 alert('请设置表单的findByKeyAction！');
    		 return;
    	 } 
    	 url = billForm.findByKeyAction + '?';
     	
     	
     	for(var i=0;i<masterkeys.length;i++){
 			var temp = eval("action.result." + masterkeys[i]);
 			if (!temp) {
 				alert('执行saveAction后没有从服务端返回对象的主键' + masterkeys[i] + '的值！');
 				break;
 			}
 			url += masterkeys[i] + '=' + temp + '&';
 		}
 		billForm.form.reset();
 		
     	//装载对象到表单
     	billForm.form.load({
 	        waitMsg : '正在载入数据...',
 	        url:  url,
     		success: function(form,action) { 
 	        	//表单载入数据时,设置特殊值
     			controller.initEditPage(action);
     			
 	        	//显示正确提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
 	        },
 	        failure: function(form,action) {
 	        	//显示错误提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
 	        }
 	   	});
     }
    
});